/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatroom;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 *
 * @author Caca
 */
public class ClientGame extends JFrame implements ActionListener{

    private JTextField jtfHost,jtfNameUser,jtfPort;
    private JButton jbBackRoom,jbJoin; 
    public JTextField jtfSend;
    private JPanel jpMapCo; // map ban co
    private JTextArea jtaStatus;
    private JLabel jlname1,jlname2; // hien thi ten cua 2 player 
    private JLabel jlExpName1,jlExpName2;
    private JLabel jlisWrite; // trang thai dang viet tin nhan
    private JLabel jlNoti;
    private Square sq; // o vuong trong ban co
    private String isMyState; // trang thai cam quan cua Client (O or X or "")
    private SimpleDateFormat sdf;
    
    public Client client;   
    private boolean joinGame;
    private JPanel contaniMap;
    private Square [][] listsq = new Square[20][20]; // map cac o vuong trong ban co
    public boolean block; // Doi doi thu danh
    private JButton jbPlayAgain;
    public String getIsMyState() {
        return isMyState;
    }
    

    public void setIsMyState(String isMyState) {
        this.isMyState = isMyState;
    }

    public boolean isBlock() {
        return block;
    }

    public void setBlock(boolean block) {
        this.block = block;
    }
    
    public void setVisiblePlayAgain(){
        if (client.onGame == true){
            jbPlayAgain.setEnabled(true);
        }else{
          jbPlayAgain.setEnabled(false);
        }
    }
    
    public void setExp(String exp, String exp2){
        jlExpName1.setText("Điểm kinh nghiệm: "+exp);
        jlExpName2.setText("Điểm kinh nghiệm: "+exp2);
    }
    
    
    public  ClientGame(){
        
        // set up variable
        isMyState = "";
        block = false;
        sdf = new SimpleDateFormat("HH:mm:ss");        
        // top 
        
        JPanel containPanel = new JPanel(new GridLayout(1, 2));
        JPanel topPanel = new JPanel(new GridLayout(1, 7, 7, 2));
        topPanel.add(new JLabel("Server Adress: "));
        jtfHost = new JTextField("localhost");       
        topPanel.add(jtfHost);
        topPanel.add(new JLabel("Port : "));        
        jtfPort = new JTextField("1500");
        jtfPort.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        topPanel.add(jtfPort);
        jtfNameUser = new JTextField("Hello");      
        topPanel.add(new JLabel("Name User: "));
        topPanel.add(jtfNameUser);
        jbJoin = new JButton("Join");
        topPanel.add(jbJoin);
        add(topPanel, BorderLayout.PAGE_START);
        
        // Map Co
        
        JPanel centerPanel = new JPanel(new GridLayout(1, 2,5, 5)); 
        contaniMap = new JPanel();
        containPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Bàn cờ: "));    
        jpMapCo = new JPanel(new GridLayout(20,20));
        jpMapCo.setSize(805, 605);
               
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                Square cell = new Square(i, j,this);
                listsq[i][j] = cell;
                listsq[i][j].setIsState("");
                jpMapCo.add(cell);
            }           
        }
        
        containPanel.add(jpMapCo);
        centerPanel.add(containPanel);
        
        // JPanel Ben pai
        JPanel rightPanel = new JPanel(new GridLayout(2, 1, 5, 5));
        
        JPanel detailPanel = new JPanel(new GridLayout(5, 1, 5, 5));
        
        JPanel detail1Panel = new JPanel(new GridLayout(1, 2, 5, 5));        
        jlname1 =  new JLabel("?Name1");
        detail1Panel.add(jlname1);
        jlExpName1 = new JLabel("?Exp1");
        detail1Panel.add(jlExpName1);
        detailPanel.add(detail1Panel);
        
        JPanel detail2Panel = new JPanel(new GridLayout(1, 2, 5, 5));
        jlname2 =  new JLabel("?Name2");
        detail2Panel.add(jlname2);
        jlExpName2 = new JLabel("?Exp2");
        detail2Panel.add(jlExpName2);
        detailPanel.add(detail2Panel);
        
        jlNoti = new JLabel("Noti: ");
        detailPanel.add(jlNoti);
        
        detailPanel.add(new JLabel(""));
        
        // JPanel: jtextSend + jlisWrite
        JPanel sendPanel =  new JPanel(new GridLayout(2, 1, 5, 5));        
        jtfSend = new JTextField("");
        sendPanel.add(jtfSend);
        // Xu ly dang viet o jtfSend
        jtfSend.addKeyListener(new java.awt.event.KeyAdapter() {
            
            public void keyReleased(java.awt.event.KeyEvent evt) {
                client.sendMessage(new ChatMessage(ChatMessage.ISWRITESTOP, "")); 
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                client.sendMessage(new ChatMessage(ChatMessage.ISWRITE, "")); 
            }
        });
       
        jlisWrite = new JLabel("??");
        jlisWrite.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        sendPanel.add(jlisWrite);
        
        
        detailPanel.add(sendPanel);
        rightPanel.add(detailPanel);
        
        
        centerPanel.add(rightPanel);
        
        JPanel contentPanel = new JPanel(new GridLayout(1, 1, 5, 5));
        contentPanel.scrollRectToVisible(null);
        contentPanel.setSize(300, 100);
        contentPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Trạng thái Client: "));        
        jtaStatus = new JTextArea("Wellcome Game !!! \n",30,40);
        jtaStatus.setEditable(false);
        contentPanel.add(new JScrollPane(jtaStatus));      
        rightPanel.add(contentPanel);        
        add(centerPanel,BorderLayout.CENTER);
        
        JPanel bottomPanel = new JPanel(new GridLayout(1, 4, 5, 5));
        bottomPanel.add(new JLabel());
        jbPlayAgain = new JButton("Play Again");
        bottomPanel.add(jbPlayAgain);        
       
        jbBackRoom = new JButton("Exit");
        jbBackRoom.setSize(30, 20);
        bottomPanel.add(jbBackRoom);
        bottomPanel.add(new JLabel());       
        add(bottomPanel,BorderLayout.PAGE_END);
        
         // Set Enable        
        jtfSend.setEnabled(false);  
        jbPlayAgain.setEnabled(false);
        jbBackRoom.setEnabled(false);
        
        // add actiomlistenr
        jbBackRoom.addActionListener(this);
        jbJoin.addActionListener(this);
        jtfSend.addActionListener(this);        
        jbPlayAgain.addActionListener(this);
        
       
        
        setDefaultCloseOperation(EXIT_ON_CLOSE);        
        setResizable(false);
        setSize(1000, 700);
	setVisible(true);
        
    }
    
    // viet ra textArea 
    public void appendStatus(String msg){
        String time = sdf.format(new Date()) + " " + msg + "\n";
        jtaStatus.append(time);
    }
    
    // cai dat jlisWrite
    public void setIsWrite(String str){
        jlisWrite.setText(str);
    }
    
    // Cai dat trang thai ban dau
    public void setGame(String username,String username2, String mark, String mark2){  
        jlname1.setText(username + " : " + mark);
        jlname2.setText(username2 + " : " + mark2);       
    }
    
    // Trang Thai game
    public void setNoti(String str){        
            jlNoti.setText(str);
    }
    // Trang thai play again, reset ban co
    public void setPlayAgain(){            
      
       if (client.myMarks.equals("O")){
           block = false;
       }else if (client.myMarks.equals("X")){
           block = true;
       }
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                setIcon(i, j, "");
            }
        }
    }
    
    // cai dat load icon
    public void setIcon(int row, int col, String isState){
        if (isState.equals("X")){
           String urlImage ="/Game/CellX.png";
           URL urlToImage = this.getClass().getResource(urlImage);
           ImageIcon icon = new ImageIcon(urlToImage);
           listsq[row][col].setIcon(icon);
           listsq[row][col].setIsState("X");
        }else if (isState.equals("O")){
           String urlImage ="/Game/CellO.png";
           URL urlToImage = this.getClass().getResource(urlImage);
           ImageIcon icon = new ImageIcon(urlToImage);
           listsq[row][col].setIcon(icon);
           listsq[row][col].setIsState("O");
        } else if (isState.equals("")){
           String urlImage ="/Game/CellNULL.png";
           URL urlToImage = this.getClass().getResource(urlImage);
           ImageIcon icon = new ImageIcon(urlToImage);
           listsq[row][col].setIcon(icon);
           listsq[row][col].setIsState("");
        }
    }
   
    // bat ca su kien cac nut
    @Override
    public void actionPerformed(ActionEvent e) {
        Object o = e.getSource();
        if(o == jtfSend){
            if (!jtfSend.getText().equals("")){
                client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, jtfSend.getText()));
                jtfSend.setText("");
            }
            return;
        }
        
        // button Exit
        if(o == jbBackRoom){
            jtfHost.setEnabled(true);
            jtfNameUser.setEnabled(true);
            jtfNameUser.setText("");
            jtfPort.setEnabled(true);
            jtfPort.setText("");
            jbJoin.setEnabled(true);
            client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, ""));            
            setNoti("Bạn vừa thoát ra khỏi room...");
            setPlayAgain();
            return;
        }
        
        // button Join
        if (o == jbJoin){
            String username = jtfNameUser.getText().trim();
            // empty username ignore it
            if (username.length() == 0) {
                return;
            }
            // empty serverAddress ignore it
            String server = jtfHost.getText().trim();
            if (server.length() == 0) {
                return;
            }
            // empty or invalid port numer, ignore it
            String portNumber = jtfPort.getText().trim();
            if (portNumber.length() == 0) {
                return;
            }
            int port = 0;
            try {
                port = Integer.parseInt(portNumber);
            } catch (Exception en) {
                return;   // nothing I can do if port number is not valid
            }

            // try creating a new Client with GUI
            client = new Client(server, port, username, this);
            // test if we can start the Client
            if (!client.start()) {
                return;
            }   

            jtfHost.setEnabled(false);
            jtfNameUser.setEnabled(false);
            jtfPort.setEnabled(false);
            jbJoin.setEnabled(false);
            jtfSend.setEnabled(true);
            jbBackRoom.setEnabled(true);           
            
            // Send message join game
            client.sendMessage(new ChatMessage(ChatMessage.JOINGAME, ""));                       
            return;
        }      
        if(o == jbPlayAgain){            
            client.sendMessage(new ChatMessage(ChatMessage.AGAIN, ""));            
            return;
        }
    }
    public class Square extends JLabel {

        private int col;
        private int row;
        private String isState;
        private ClientGame clientGame;
        private boolean onGame;
        ChatMessage cm;

        public String getIsState() {
            return isState;
        }

        public void setIsState(String isState) {
            this.isState = isState;
        }

        public int getCol() {
            return col;
        }

        public void setCol(int col) {
            this.col = col;
        }

        public int getRow() {
            return row;
        }

        public void setRow(int row) {
            this.row = row;
        }

        public Square(int row, int col, ClientGame cg) {
            this.row = row;
            this.col = col;
            this.clientGame = cg;
            String urlImage = "/Game/CellNULL.png";
            URL urlToImage = this.getClass().getResource(urlImage);
            ImageIcon icon = new ImageIcon(urlToImage);
            setIcon(icon);


            this.addMouseListener(new MouseListener() {
                @Override
                public void mouseClicked(MouseEvent e) {
                }

                @Override
                public void mousePressed(MouseEvent e) {
                    // bam chuot vao ban co
                    if (clientGame.getIsMyState() != "") {
                        if (client.isWin == true){
                            block = true;
                        }
                        if (block == false){
                            if (listsq[getRow()][getCol()].getIsState().equals("")){
                                    client.sendMessage(new ChatMessage(ChatMessage.MOVES, "Move " + clientGame.getIsMyState() + " : " + getRow() + "," + getCol()));
                                    setNoti("Đợi  " + client.username2 + " đánh..."); 
                                    block = true;
                            }
                        }
                    }
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                }

                @Override
                public void mouseEntered(MouseEvent e) {
                }

                @Override
                public void mouseExited(MouseEvent e) {
                }
            });
        }

        public void loadIcon(String myState) {
            String urlImage;
            if (myState == "X") {
                urlImage = "/Game/CellX.png";
                URL urlToImage = this.getClass().getResource(urlImage);
                ImageIcon icon = new ImageIcon(urlToImage);
                setIcon(icon);
            } else if (myState == "O") {
                urlImage = "/Game/CellO.png";
                URL urlToImage = this.getClass().getResource(urlImage);
                ImageIcon icon = new ImageIcon(urlToImage);
                setIcon(icon);
            } else if (myState == "") {
                urlImage = "/Game/CellNULL.png";
                URL urlToImage = this.getClass().getResource(urlImage);
                ImageIcon icon = new ImageIcon(urlToImage);
                setIcon(icon);
            }

        }
    }

    public static void main(String[] args) {
        ClientGame cg = new ClientGame();
    }
}
